package com.jason.game.online.home

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.cby.library.common.base.BaseViewModel
import com.cby.library.common.base.DataWrapper
import com.cby.library.common.network.BaseResponse
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.cby.library.data.model.HomeBean
import com.cby.library.data.model.ModuleBean
import com.cby.library.data.model.TYPE_NONE
import com.cby.library.data.repository.HomeApiImpl
import com.cby.library.data.repository.parser.HomeModuleJsonParser
import kotlinx.coroutines.launch
import java.io.StringReader
import java.lang.Exception
import java.util.ArrayList

/**
 * @description: MainViewModel
 *
 * @author ChenBaoyang
 * @date 2021/10/20 19:11
 */
class HomeViewModel(application: Application) : BaseViewModel(application) {

    val homeData = MutableLiveData<DataWrapper<HomeBean>>()

    val homeApi = HomeApiImpl()

    fun loadData() {
        viewModelScope.launch {
            showLoading()
            try {
                val response = homeApi.getHomeData()
                val homeBean = parserHomeData(response)
                homeData.postValue(DataWrapper.success(homeBean))
                showContent()
            }catch (e: Exception) {
                showError(e.toString())
            }
        }
    }

    private fun parserHomeData(response: String) : HomeBean {
        val gson = GsonBuilder()
            .registerTypeAdapter(ModuleBean::class.java, HomeModuleJsonParser())
            .enableComplexMapKeySerialization()
            .serializeNulls()
            .create()

        val jsonReader = JsonReader(
            StringReader(
                handleSpecialJsonString(response)
            )
        )
        jsonReader.isLenient = true

        val responseData: BaseResponse<HomeBean> = gson.fromJson(
            jsonReader,
            object : TypeToken<BaseResponse<HomeBean?>?>() {}.type
        )

        val resultData: HomeBean = responseData.data

        //过滤不在当前版本排版的数据
        //过滤不在当前版本排版的数据
        val modules: MutableList<ModuleBean> = ArrayList<ModuleBean>()
        for (entity: ModuleBean? in resultData.modules!!)
        {
            if (entity != null) {
                if (TYPE_NONE == entity.displayStyle) {
                    continue
                }
                modules.add(entity)
            }
        }

        resultData.modules = modules
        return resultData
    }

    /**
     * 针对json中含有转义符进行处理，避免出现未结束解析异常
     */
    private fun handleSpecialJsonString(oldJson: String): String? {
        val temp = oldJson.toCharArray()
        val n = temp.size
        for (i in 0 until n) {
            if (temp[i] == ':' && temp[i + 1] == '"' && temp[i + 2] != ',') {
                for (j in i + 2 until n) {
                    if (temp[j] == '"') {
                        if (temp[j + 1] != ',' && temp[j + 1] != '}') {
                            temp[j] = '”'
                        } else if (temp[j + 1] == ',' || temp[j + 1] == '}') {
                            break
                        }
                    }
                }
            }
        }
        return String(temp)
    }


}